﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;

using SharedGenomics.Core;

namespace SharedGenomics.Workbench.Core
{
    public class LoginManager : ILoginManager
    {
        private bool _isLoggedIn;
        private UserCredentials loginCredentials;
        private IAuthenticationService authenticationService;

        public LoginManager(IAuthenticationService authenticationService)
        {
            this.AuthenticationService = authenticationService;
        }

        public event EventHandler IsLoggedInChanged;

        public bool TryLogin(string userName, SecureString password, out string errorMessage)
        {
            UserCredentials uc = new UserCredentials(userName, password);

            bool loginSuccessful = this.AuthenticationService.TryAuthenticate(uc, out errorMessage);
            if (loginSuccessful)
            {
                this.IsLoggedIn = true;
                this.LoginCredentials = uc;
            }

            return loginSuccessful;
        }

        public void Logoff()
        {
            if (this.IsLoggedIn)
            {
                this.IsLoggedIn = false;
            }
            else
            {
                throw new InvalidOperationException("User is not currently logged in");
            }
        }

        public bool IsLoggedIn
        {
            get { return this._isLoggedIn; }
            private set
            {
                bool changing = this._isLoggedIn ^ value;
                this._isLoggedIn = value;

                //raise event if logged-in status has changed
                if (changing)
                    this.IsLoggedInChanged.Raise(this);
            }
        }

        public UserCredentials LoginCredentials
        {
            get
            {
                if (this.IsLoggedIn)
                {
                    return this.loginCredentials;
                }
                else
                {
                    throw new InvalidOperationException("User is not logged in");
                }
            }
            private set { this.loginCredentials = value; }
        }

        private IAuthenticationService AuthenticationService
        {
            get { return this.authenticationService; }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("AuthenticationService");

                this.authenticationService = value;
            }
        }
    }
}
